<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="title" label="标题">
        <uni-easyinput placeholder="标题" v-model="formData.title" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="user_name" label="文章作者">
        <uni-easyinput placeholder="请输入作者名称" v-model="formData.user_name"></uni-easyinput>
      </uni-forms-item>
	  <uni-forms-item name="avatar" label="封面大图">
	    <uni-file-picker return-type="object" v-model="formData.avatar"></uni-file-picker>
	  </uni-forms-item>
      <uni-forms-item name="content" label="公司简介">
        <!-- <uni-easyinput placeholder="公司简介" v-model="formData.content" trim="right"></uni-easyinput> -->
		<div id="content">
			<div v-html="formData.content"></div>
		</div>
      </uni-forms-item>
      <uni-forms-item name="article_status" label="文章状态">
        <uni-data-checkbox v-model="formData.article_status" :localdata="formOptions.article_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/sys_company_info.js';
import E from 'wangeditor';
  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'sys_company_info';
let editor = null;

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "title": "",
        "user_name": "",
        "content": "",
        "avatar": null,
        "article_status": 1
      }
      return {
        formData,
        formOptions: {
          "article_status_localdata": [
            {
              "value": 0,
              "text": "草稿箱"
            },
            {
              "value": 1,
              "text": "已发布"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules);
	  this.onLoadWangEdit();
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
		value.content = editor.txt.html();
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("title,user_name,content,avatar,article_status").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
	  
	  onLoadWangEdit() {
	  	editor = new E('#content')
	  	editor.config.zIndex = 0
	  
	  	editor.config.customUploadImg = function(resultFiles, insertImgFn) {
	  		// resultFiles 是 input 中选中的文件列表
	  		// insertImgFn 是获取图片 url 后，插入到编辑器的方法
	  
	  		// 上传图片，返回结果，将图片插入到编辑器中
	  		resultFiles.forEach(item => {
	  			let path = URL.createObjectURL(item);
	  			let fileName = item.name + Date.now();
	  			uniCloud.uploadFile({
	  				filePath: path,
	  				cloudPath: fileName
	  			}).then(res => {
	  				console.log(res);
	  				insertImgFn(res.fileID)
	  			})
	  		})
		}
	  
	  	editor.config.onblur = (newHtml) => {
	  		this.formData.content = newHtml
	  	};
		
		/* editor.config.onfocus = function (newHtml) {
		    console.log('onfocus', newHtml) // 获取最新的 html 内容
		}; */
	  
	  	editor.create()
	  }
    }
  }
</script>
